package com.cloud.job.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.api.domain.job.ArealDistribution;
import com.cloud.api.domain.report.ArealDistributionExcel;
import com.cloud.api.utils.ExcelUtils;
import com.cloud.job.config.MysqlConfig;
import com.cloud.job.mapper.ArealDistributionMapper;
import com.cloud.job.service.EmailService;
import com.cloud.job.service.IArealDistributionService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

/**
 * @author 杨斌
 * 2024-03-1/3/2024
 */
@Service("arealDistributionService")
@DS("doris")
public class ArealDistributionServiceImpl extends ServiceImpl<ArealDistributionMapper, ArealDistribution> implements IArealDistributionService {
    @Resource
    private ArealDistributionMapper arealDistributionMapper;
    @Resource
    private MessageSource messageSource;

    @Autowired
    private MysqlConfig mysqlConfig;
    @Autowired
    private EmailService emailService;
    @Override
    public void exportMailArealDistributionList() {
        Locale locale = LocaleContextHolder.getLocale();
        String fileName = "table.arealDistribution";
        List<ArealDistributionExcel> data = arealDistributionMapper.exportArealDistributionList(mysqlConfig.getDataSource());
        fileName = messageSource.getMessage(fileName, null, fileName, locale);
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            // 导出Excel文件到ByteArrayOutputStream
            ExcelUtils.export(outputStream, fileName, data, ArealDistributionExcel.class);
            // 获取字节数组副本，用于后续邮件发送
            byte[] fileBytes = outputStream.toByteArray();
            // 异步发送邮件
            emailService.sendEmailAsync("车辆各省市数据分布导出", "请查看附件中的车辆各省市数据分布数据。", fileName + ".xlsx", fileBytes);
        } catch (IOException e) {
            log.error("导出Excel文件失败", e);
        }
    }

    @Override
    public List<ArealDistributionExcel> getArealDistributionData() {
        return arealDistributionMapper.exportArealDistributionList(mysqlConfig.getDataSource());
    }
}
